#include "Region.h"
#include "Utils.h"
#include "Fonts.h"
#include <sfml/Graphics.hpp>

Region::Region(){}
Region::Region(float top , float left , float bottom , float right , int id ) 
		: m_top(top),
			m_left(left),
			m_bottom(bottom),
			m_right(right),
			m_id(id)
{
	m_width = fabs(m_left - m_right);
	m_height = fabs(m_top - m_bottom);

	m_center = Vector2( (m_left + m_right)*0.5f, (m_top + m_bottom)*0.5f );
}

/*
To build squared region, given center and apothem.
*/
Region::Region(Vector2 center, float apothem, int id)
		: m_id(id)
{
	if(apothem < 0.f)
		apothem = 0.f;

	m_top = center.y - apothem;
	m_left = center.x - apothem;
	m_bottom = center.y + apothem;
	m_right = center.x + apothem;
	m_center = center;
	m_width = m_height = 2 * apothem;
}

Region Region::IntersectionWith(const Region &other) const
{
	float top = (m_top >= other.Top())? m_top : other.Top();
	float left = (m_left >= other.Left())? m_left : other.Left();
	float bottom = (m_bottom <= other.Bottom())? m_bottom : other.Bottom();
	float right = (m_right <= other.Right())? m_right : other.Right();

	if (top < bottom && left < right)
		return Region(top, left, bottom, right);

	return Region(0, 0, 0, 0, -1000);
}
bool Region::Inside(const Vector2 &pos)
{
	return (pos.x >= m_left && pos.x <= m_right && pos.y >= m_top && pos.y <= m_bottom)  ;
}

Vector2 Region::RandomPosition() const
{
	return Vector2( RandBetween(m_left,m_right), RandBetween(m_top, m_bottom) );
}

Vector2 Region::RandomCenterPosition() const
{
	return Vector2( m_center.x + RandBetween(-20,20), m_center.y + RandBetween(-20,20) );
}

void Region::OnDraw(sf::RenderWindow &window)
{
	window.SaveGLStates();
	sf::Shape rect = sf::Shape::Rectangle(m_left, m_top, m_width, m_height, sf::Color::Black,1.f, sf::Color::Black);
	rect.EnableFill(false);
	rect.EnableOutline(true);

	sf::Font* f = Fonts::Istance()->GetFont("Consola");
	sf::Text text(NumberToString(m_id), (*f), 18);
	text.SetPosition(sf::Vector2f(m_center.x - text.GetRect().Width/2, m_center.y - text.GetRect().Height/2));
	
	window.Draw(rect);
	window.Draw(text);
	window.RestoreGLStates();
}